﻿using Common.Extensions;
using Common.Utility;
using Interface.Volcengine.DTO;
using Interface.Volcengine.DTO.CVProcess;

namespace Interface.Volcengine
{
    public class VolcengineApi
    {
        private readonly IHttpClientFactory _httpClientFactory;

        private string CVProcessApiUrl = $"{AppSetting.GetAppSetting("Volcengine:Url")}?Action={AppSetting.GetAppSetting("Volcengine:CVProcess:Action")}&Version={AppSetting.GetAppSetting("Volcengine:CVProcess:Version")}";

        public VolcengineApi(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<CVProcessResponse> CVProcessAsync(string prompt)
        {
            var requestBody = new CVProcessRequest
            {
                Prompt = prompt
            };

            VolcengineSigner _signer = new VolcengineSigner(AppSetting.GetAppSetting("Volcengine:CVProcess:Region"), AppSetting.GetAppSetting("Volcengine:CVProcess:Service"));
            var headers = _signer.GenerateHeaders("POST", CVProcessApiUrl, requestBody);

            var _httpClient = _httpClientFactory.CreateClient();
            var httpResponse = await _httpClient.HttpPost<VolcengineResponseBase<CVProcessResponse>>(CVProcessApiUrl, headers, requestBody);
            if (!httpResponse.IsSuccess)
            {
                throw new Exception(httpResponse.Msg);
            }
            if(httpResponse.Data.ResponseMetadata != null)
            {
                throw new Exception(httpResponse.Data.ResponseMetadata.Error.Message);
            }
            if (!httpResponse.Data.IsSuccess)
            {
                throw new Exception(httpResponse.Data.Message);
            }
            return httpResponse.Data.Data;
        }
    }
}
